import CryptoJS from 'crypto-js'

/**
 * AES 加密工具（对齐 Dart 版本）
 */
export class SecurityUtils {
  private static getEncryptKey() {
    return import.meta.env.VITE_ENCRYPT_KEY || 'wbdalegalencrypt'
  }

  private static getConvertKey() {
    return import.meta.env.VITE_CONVERT_KEY || 'iamwalkerencrypt'
  }

  private static getKey(adConvert: boolean) {
    const keyStr = adConvert
      ? SecurityUtils.getConvertKey()
      : SecurityUtils.getEncryptKey()

    // CryptoJS AES 要求 WordArray
    return CryptoJS.enc.Utf8.parse(keyStr)
  }

  /**
   * 加密文本
   */
  static encrypt(plainText: string, adConvert = false): string {
    const key = SecurityUtils.getKey(adConvert)
    const encrypted = CryptoJS.AES.encrypt(plainText, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    })
    return encrypted.toString() // base64
  }

  /**
   * 解密密文（base64）
   */
  static decrypt(cipherText: string, adConvert = false): string {
    const key = SecurityUtils.getKey(adConvert)
    const decrypted = CryptoJS.AES.decrypt(cipherText, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    })
    return CryptoJS.enc.Utf8.stringify(decrypted)
  }
}
